package com.thinkcube.edutainment;

import java.io.File;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.TextChange;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.ActionBar.OnMenuVisibilityListener;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bugsense.trace.BugSenseHandler;
//import com.bugsense.trace.BugSenseHandler;
import com.example.google.tv.leftnavbar.LeftNavBar;
import com.example.google.tv.leftnavbar.LeftNavBarService;
import com.thinkcube.edutainment.fragment.HomeFragment;
import com.thinkcube.edutainment.fragment.MessageMainFragment;
import com.thinkcube.edutainment.fragment.MessageMainFragment_;
import com.thinkcube.edutainment.fragment.MyCourseDashBordMainFragment;
import com.thinkcube.edutainment.fragment.MyFragment;
import com.thinkcube.edutainment.fragment.NoticeDialogFragment;
import com.thinkcube.edutainment.fragment.NoticeDialogFragment.onSubmitListener;
import com.thinkcube.edutainment.fragment.UserFragment;
import com.thinkcube.edutainment.service.SPreferences_;

@EActivity(R.layout.home)
public class LoginActivity extends FragmentActivity implements onSubmitListener {
	/** Called when the activity is first created. */

	@ViewById(R.id.searchText)
	TextView searchText;

	@AfterViews
	void iniUi() {

		BugSenseHandler.initAndStartSession(LoginActivity.this,
				EdutainmentConstant.BUG_SENSE_APIKEY);
		
//		Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
//            @Override
//            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
//                Log.e("LoginActivity", "OMG! Uncaught Exception!");
//                // Without calling System.exit() this will not work.
//				System.exit(2);
//            }
//        });

		// pref.getId().put("526a2e6bd707e20f52e600d5");
		// pref.getId().put("5268e248d707e2da06b03e64");

		LeftNavBar bar = (LeftNavBarService.instance()).getLeftNavBar(this);
		flipOption(ActionBar.DISPLAY_SHOW_TITLE);
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		flipOption(LeftNavBar.DISPLAY_AUTO_EXPAND);

		bar.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.leftnav_bar_background_dark));
		// setupButtons();
		// Prepare the left navigation bar.

		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		// add a fragment
		HomeFragment homeFrag = new HomeFragment();
		fragmentTransaction.add(R.id.myfragment, homeFrag);
		fragmentTransaction.commit();

		setupBar();

	}

	@TextChange(R.id.searchText)
	void onTextChangesOnUserName(final CharSequence text, final TextView hello,
			final int before, final int start, final int count) {

		FragmentManager fragmentManager = getFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();

		// add a fragment
		MyFragment myFragment = new MyFragment();
		fragmentTransaction.add(R.id.myfragment, myFragment);
		fragmentTransaction.commit();
	}

	@Click(R.id.searchText)
	void onClick(View view) {

		if (view.getId() == R.id.searchText) {

			FragmentManager fragmentManager = getFragmentManager();
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();

			// add a fragment
			MyFragment myFragment = new MyFragment();
			fragmentTransaction.add(R.id.myfragment, myFragment);
			fragmentTransaction.commit();

		}

	}

	private static final ActionBar.TabListener BLANK_LISTENER = new ActionBar.TabListener() {
		@Override
		public void onTabSelected(final Tab tab, final FragmentTransaction ft) {

		}

		@Override
		public void onTabUnselected(final Tab tab, final FragmentTransaction ft) {
		}

		@Override
		public void onTabReselected(final Tab tab, final FragmentTransaction ft) {
		}
	};
	private boolean mHasCustomTabs;
	private LeftNavBar mLeftNavBar;

	@Pref
	SPreferences_ pref;

	private LeftNavBar getLeftNavBar() {
		if (mLeftNavBar == null) {
			mLeftNavBar = new LeftNavBar(this);
			mLeftNavBar.setOnClickHomeListener(new View.OnClickListener() {
				@Override
				public void onClick(final View v) {

				}
			});
			mLeftNavBar
					.addOnMenuVisibilityListener(new OnMenuVisibilityListener() {

						@Override
						public void onMenuVisibilityChanged(boolean isVisible) {

						}
					});

		}
		return mLeftNavBar;
	}

	private void setupBar() {
		ActionBar bar = getLeftNavBar();
		bar.setTitle(R.string.title_text);
		setupCustomView();

		// Tabs.
		setupTabs(mHasCustomTabs);

	}

	private void setupCustomView() {
		getLeftNavBar().setCustomView(R.layout.custom_view);
		LayoutParams params = new LayoutParams(0);
		params.width = params.height = nextDimension(0);
		params.gravity = nextGravity(nextGravity(0, true), false);
		applyCustomParams(params);
	}

	private void applyCustomParams(final LayoutParams params) {
		ActionBar bar = getLeftNavBar();
		bar.setCustomView(bar.getCustomView(), params);
	}

	private static int nextDimension(final int dimension) {
		switch (dimension) {
		case 40:
			return 100;
		case 100:
			return LayoutParams.MATCH_PARENT;
		case LayoutParams.MATCH_PARENT:
		default:
			return 40;
		}
	}

	private static int nextGravity(final int gravity, final boolean horizontal) {
		int hGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
		int vGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
		if (horizontal) {
			switch (hGravity) {
			case Gravity.LEFT:
				hGravity = Gravity.CENTER_HORIZONTAL;
				break;
			case Gravity.CENTER_HORIZONTAL:
				hGravity = Gravity.RIGHT;
				break;
			case Gravity.RIGHT:
			default:
				hGravity = Gravity.LEFT;
				break;
			}
		} else {
			switch (vGravity) {
			case Gravity.TOP:
				vGravity = Gravity.CENTER_VERTICAL;
				break;
			case Gravity.CENTER_VERTICAL:
				vGravity = Gravity.BOTTOM;
				break;
			case Gravity.BOTTOM:
			default:
				vGravity = Gravity.TOP;
				break;
			}
		}
		return hGravity | vGravity;
	}

	private void setupTabs(final boolean custom) {
		ActionBar bar = getLeftNavBar();
		bar.removeAllTabs();
		if (custom) {
			addCustomTab(bar, R.string.tab_a);
			addCustomTab(bar, R.string.tab_b);
			// addCustomTab(bar, R.string.tab_c);
			addCustomTab(bar, R.string.tab_d);
			addCustomTab(bar, R.string.tab_e);
		} else {

			ActionBar.Tab tab = bar.newTab().setText(R.string.tab_a)
					.setIcon(R.drawable.tab_a)
					.setTabListener(new ActionBar.TabListener() {

						@Override
						public void onTabUnselected(final Tab tab,
								final FragmentTransaction ft) {

						}

						@Override
						public void onTabSelected(final Tab tab,
								final FragmentTransaction ft) {
							System.out.println("onTabSelected");
							FragmentManager fragmentManager = getFragmentManager();
							FragmentTransaction fragmentTransaction = fragmentManager
									.beginTransaction();

							// add a fragment
							HomeFragment homeFragment = new HomeFragment();
							fragmentTransaction.replace(R.id.myfragment,
									homeFragment);
							fragmentTransaction.addToBackStack(null);
							fragmentTransaction.commit();
						}

						@Override
						public void onTabReselected(final Tab tab,
								final FragmentTransaction ft) {
							System.out.println("onTabReselected");
							FragmentManager fragmentManager = getFragmentManager();
							FragmentTransaction fragmentTransaction = fragmentManager
									.beginTransaction();

							// add a fragment
							HomeFragment homeFragment = new HomeFragment();
							fragmentTransaction.replace(R.id.myfragment,
									homeFragment);
							fragmentTransaction.commit();
						}
					});
			bar.addTab(
					bar.newTab().setText(R.string.tab_b)
							.setIcon(R.drawable.tab_b)
							.setTabListener(new TabListener() {

								@Override
								public void onTabUnselected(Tab tab,
										FragmentTransaction ft) {

								}

								@Override
								public void onTabSelected(Tab tab,
										FragmentTransaction ft) {

									FragmentManager fragmentManager = getFragmentManager();
									FragmentTransaction fragmentTransaction = fragmentManager
											.beginTransaction();

									fragmentTransaction.replace(
											R.id.myfragment,
											MyCourseDashBordMainFragment
													.newInstance());
									fragmentTransaction.addToBackStack(null);
									fragmentTransaction.commit();
								}

								@Override
								public void onTabReselected(Tab tab,
										FragmentTransaction ft) {

									FragmentManager fragmentManager = getFragmentManager();
									FragmentTransaction fragmentTransaction = fragmentManager
											.beginTransaction();

									fragmentTransaction.replace(
											R.id.myfragment,
											MyCourseDashBordMainFragment
													.newInstance());
									fragmentTransaction.addToBackStack(null);
									fragmentTransaction.commit();

								}
							}), false);
			bar.addTab(tab, 0, true);
			// bar.addTab(
			// bar.newTab().setText(R.string.tab_c)
			// .setIcon(R.drawable.tab_c)
			// .setTabListener(new TabListener() {
			//
			// @Override
			// public void onTabUnselected(Tab tab,
			// FragmentTransaction ft) {
			// // TODO Auto-generated method stub
			// }
			//
			// @Override
			// public void onTabSelected(Tab tab,
			// FragmentTransaction ft) {
			// // TODO Auto-generated method stub
			// FragmentManager fragmentManager = getFragmentManager();
			// FragmentTransaction fragmentTransaction = fragmentManager
			// .beginTransaction();
			//
			// // add a fragment
			// MyFragment3 myFragment = new MyFragment3();
			//
			// fragmentTransaction.replace(
			// R.id.myfragment, myFragment);
			// fragmentTransaction.commit();
			// }
			//
			// @Override
			// public void onTabReselected(Tab tab,
			// FragmentTransaction ft) {
			// // TODO Auto-generated method stub
			//
			// }
			// }), false);
			bar.addTab(
					bar.newTab().setText(R.string.tab_d)
							.setIcon(R.drawable.tab_d)
							.setTabListener(new TabListener() {

								@Override
								public void onTabUnselected(Tab tab,
										FragmentTransaction ft) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onTabSelected(Tab tab,
										FragmentTransaction ft) {

									FragmentManager fragmentManager = getFragmentManager();
									FragmentTransaction fragmentTransaction = fragmentManager
											.beginTransaction();

									// add a fragment
									MessageMainFragment myFragment = new MessageMainFragment_();
									fragmentTransaction.replace(
											R.id.myfragment, myFragment);
									fragmentTransaction.commit();
								}

								@Override
								public void onTabReselected(Tab tab,
										FragmentTransaction ft) {

									FragmentManager fragmentManager = getFragmentManager();
									FragmentTransaction fragmentTransaction = fragmentManager
											.beginTransaction();

									// add a fragment
									MessageMainFragment myFragment = new MessageMainFragment_();
									fragmentTransaction.replace(
											R.id.myfragment, myFragment);
									fragmentTransaction.commit();

								}
							}), false);

			bar.addTab(
					bar.newTab().setText(R.string.tab_e)
							.setIcon(R.drawable.tab_e)
							.setTabListener(new TabListener() {

								@Override
								public void onTabUnselected(Tab tab,
										FragmentTransaction ft) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onTabSelected(Tab tab,
										FragmentTransaction ft) {
									
									FragmentManager fragmentManager = getFragmentManager();
									FragmentTransaction fragmentTransaction = fragmentManager
											.beginTransaction();

									fragmentTransaction.replace(
											R.id.myfragment,
											UserFragment.newInstance());
									fragmentTransaction.addToBackStack(null);
									fragmentTransaction.commit();
								}

								@Override
								public void onTabReselected(Tab tab,
										FragmentTransaction ft) {
									// TODO Auto-generated method stub

								}
							}), false);
		}
	}

	private void addCustomTab(final ActionBar bar, final int title) {
		ActionBar.Tab tab = bar.newTab().setCustomView(R.layout.custom_tab)
				.setTabListener(BLANK_LISTENER);
		((Button) tab.getCustomView()).setText(title);
		bar.addTab(tab);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		BugSenseHandler.closeSession(LoginActivity.this);
	}

	private void flipOption(final int option) {
		ActionBar bar = getLeftNavBar();
		int options = bar.getDisplayOptions();

		boolean hadOption = (options & option) != 0;
		bar.setDisplayOptions(hadOption ? 0 : option, option);
	}

	@Override
	public void onBackPressed() {

		getFragmentManager().popBackStack();

		if (getFragmentManager().getBackStackEntryCount() == 0) {

			showExitAlertDialog();
		}

	}

	@Override
	public void onDialogOkClick(String s) {
		trimCache(this);

		this.finish();
	}

	@Override
	public void onDialogCancelClick(String a) {

		dialog.dismiss();
	}

	onSubmitListener mListener;
	String msgtext;
	NoticeDialogFragment dialog;

	void showExitAlertDialog() {

		dialog = new NoticeDialogFragment();
		dialog.mListener = this;
		dialog.msgtext = "Do you want exit?";
		dialog.show(getFragmentManager(), "NoticeDialogFragment");

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		try {
			trimCache(this);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void trimCache(Context context) {
		try {
			System.out.println("trimCache");
			File dir = context.getCacheDir();
			if (dir != null && dir.isDirectory()) {
				deleteDir(dir);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static boolean deleteDir(File dir) {
		if (dir != null && dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}

		// The directory is now empty so delete it
		return dir.delete();
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent i) {
		
		super.onActivityResult(requestCode, resultCode, i);
		
		 if((requestCode==1)&&(resultCode==1)) 
		 {
			 System.out.println("RESULT ACAATZIZVZZIZTY");
		 }
	}

}